package com.jinwei.qunguanjia.exception;

import com.jinwei.qunguanjia.common.core.domain.Response;
import com.jinwei.qunguanjia.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理器
 * 
 * @author ruoyi
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} ,不支持 {} 请求", requestURI, e.getMethod());
        return Response.fail(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public Response handleServiceException(ServiceException e) {
        return Response.fail(e.getCode(), e.getMsg());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Response handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} ,发生未知异常.", requestURI, e);
        return Response.fail();
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} ,发生系统异常.", requestURI, e);
        return Response.fail();
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Response handleBindException(BindException e) {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Response.fail(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Response handleBindException(ConstraintViolationException e) {
        String message = e.getMessage();
        return Response.fail(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        String message = "";
        if(null != fieldError){
            message = fieldError.getDefaultMessage();
        }
        return Response.fail(message);
    }
}
